<template>
  <div class="students-page">
    <div class="page-header">
      <h2 class="page-title">学生管理</h2>
      <div class="header-actions">
        <el-tag 
          v-if="selectedClass && route.query.class" 
          type="info" 
          closable 
          @close="clearClassFilter"
          class="class-filter-tag"
        >
          当前班级：{{ selectedClass }}
        </el-tag>
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          添加学生
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="hover">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8" :md="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索学生姓名或学号"
            @input="handleSearch"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="selectedClass" placeholder="选择班级" clearable @change="handleClassFilter">
            <el-option
              v-for="cls in appStore.classes"
              :key="cls.id"
              :label="cls.name"
              :value="cls.name"
            />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="selectedGender" placeholder="选择性别" clearable @change="handleGenderFilter">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-col>
      </el-row>
    </el-card>

    <!-- 学生列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="filteredStudents"
        v-loading="studentStore.loading"
        stripe
        @row-click="handleRowClick"
        class="students-table"
      >
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === '男' ? 'primary' : 'danger'">
              {{ row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="class_name" label="班级" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click.stop="viewStudent(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button size="small" type="primary" @click.stop="editStudent(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click.stop="deleteStudent(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑学生对话框 -->
    <el-dialog
      :title="isEditing ? '编辑学生' : '添加学生'"
      v-model="showAddDialog"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="studentFormRef"
        :model="studentForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="学号" prop="student_id">
          <el-input v-model="studentForm.student_id" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="studentForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="studentForm.age" :min="16" :max="30" />
        </el-form-item>
        <el-form-item label="班级" prop="class_name">
          <el-select v-model="studentForm.class_name" placeholder="请选择班级">
            <el-option
              v-for="cls in appStore.classes"
              :key="cls.id"
              :label="cls.name"
              :value="cls.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="studentForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ isEditing ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStudentStore } from '../stores/student'
import { useAppStore } from '../stores/app'

const router = useRouter()
const route = useRoute()
const studentStore = useStudentStore()
const appStore = useAppStore()

// 响应式数据
const showAddDialog = ref(false)
const isEditing = ref(false)
const searchKeyword = ref('')
const selectedClass = ref('')
const selectedGender = ref('')
const studentFormRef = ref()

// 学生表单数据
const studentForm = reactive({
  id: null,
  student_id: '',
  name: '',
  gender: '男',
  age: 18,
  class_name: '',
  phone: '',
  email: '',
  address: ''
})

// 表单验证规则
const formRules = {
  student_id: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{10}$/, message: '学号必须是10位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  class_name: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 计算属性 - 过滤后的学生列表
const filteredStudents = computed(() => {
  let students = studentStore.students

  // 先应用搜索过滤
  if (searchKeyword.value) {
    students = students.filter(student => 
      student.name.includes(searchKeyword.value) || 
      student.student_id.includes(searchKeyword.value) ||
      student.class_name.includes(searchKeyword.value)
    )
  }

  // 然后应用班级过滤
  if (selectedClass.value) {
    students = students.filter(student => student.class_name === selectedClass.value)
  }

  // 最后应用性别过滤
  if (selectedGender.value) {
    students = students.filter(student => student.gender === selectedGender.value)
  }

  return students
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleClassFilter = () => {
  // 班级过滤逻辑已在计算属性中处理
}

const handleGenderFilter = () => {
  // 性别过滤逻辑已在计算属性中处理
}

const clearClassFilter = () => {
  selectedClass.value = ''
  // 清除URL中的query参数
  router.replace({ path: '/students' })
  ElMessage.success('已清除班级过滤')
}

const handleRowClick = (row) => {
  viewStudent(row)
}

const viewStudent = (student) => {
  router.push(`/students/${student.id}`)
}

const editStudent = (student) => {
  isEditing.value = true
  showAddDialog.value = true
  Object.assign(studentForm, student)
}

const deleteStudent = async (student) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生"${student.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await studentStore.deleteStudent(student.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  console.log('提交表单:', studentForm)
  try {
    await studentFormRef.value.validate()
    console.log('表单验证通过')
    
    if (isEditing.value) {
      console.log('更新学生:', studentForm.id, studentForm)
      await studentStore.updateStudent(studentForm.id, studentForm)
      ElMessage.success('更新成功')
    } else {
      console.log('添加学生:', studentForm)
      await studentStore.addStudent(studentForm)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== 'cancel') {
      ElMessage.error(isEditing.value ? '更新失败' : '添加失败')
    }
  }
}

const resetForm = () => {
  isEditing.value = false
  Object.assign(studentForm, {
    id: null,
    student_id: '',
    name: '',
    gender: '男',
    age: 18,
    class_name: '',
    phone: '',
    email: '',
    address: ''
  })
  if (studentFormRef.value) {
    studentFormRef.value.resetFields()
  }
}

// 生命周期
onMounted(async () => {
  try {
    await Promise.all([
      studentStore.fetchStudents(),
      appStore.fetchClasses()
    ])
    
    // 检查是否有来自班级管理页面的班级参数
    if (route.query.class) {
      selectedClass.value = route.query.class
      ElMessage.info(`已筛选显示班级：${route.query.class}`)
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
})
</script>

<style scoped>
.students-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.class-filter-tag {
  font-size: 13px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.students-table {
  cursor: pointer;
}

.students-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.action-buttons {
  display: flex;
  flex-direction: row;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-card .el-col {
    margin-bottom: 10px;
  }
  
  .students-table {
    font-size: 12px;
  }
}
</style> 